<?php
use Inationsoft\NS\Core\Model;
use Inationsoft\NS\Core\Config;
use Inationsoft\NS\Database\Database;

class SystemModel extends Model {
	function __construct() {
		$this->Database = Database::getInstance();
	}

	function getConfig($group = 'system') {
		$config = array();

		$result = $this->Database->query("SELECT * FROM koma_configs WHERE config_group = '" . $group . "'");
		while($row = $this->Database->fetchAssoc($result)) {
			$config[$row['config_name']] = $row['config_value'];
		}

		return $config;
	}

	function getUser($username = '', $password = '') {
		if($username == '' || $password == '') return false;

		$result	= $this->Database->query("
			SELECT u.uid, u.username, u.fullname, u.status, ur.rid, r.role
			FROM " . $this->Database->prefix('users') . " u, " . $this->Database->prefix('users_roles') . " ur, " . $this->Database->prefix('roles') . " r
			WHERE u.username = '" . $this->Database->escape($username) . "' AND u.password = '" . md5($this->Database->escape($password)) . "' AND ur.uid = u.uid AND r.rid = ur.rid");

		$is_first = true;
		$user = array();

		while($user_data = $this->Database->fetchAssoc($result)) {
			if($is_first) {
				$user['UID'] = $user_data['uid'];
				$user['Role'][$user_data['rid']] = $user_data['role'];
				$user['Username'] = $user_data['username'];
				$user['FullName'] = $user_data['fullname'];
				$user['Status'] = $user_data['status'];
				//$user['Token'] = md5(time() . Config::getInstance()->Application->Salt);

				$this->Database->query("UPDATE " . $this->Database->prefix('users') . " SET last_visit_time = " . time() . " WHERE uid = '" . $user_data['uid'] . "'");
				$is_first = false;
			} else {
				if($user['UID'] != $user_data['uid']) continue;
				$user['Role'][$user_data['rid']] = $user_data['role'];
			}
		}

		return (!$is_first ? $user : false);
	}

	function getBlock() {
		$block = array();

		$result = $this->Database->query("SELECT b.*, a.* FROM koma_blocks b, koma_applications a WHERE a.application_id = b.application_id");
		while($row = $this->Database->fetchAssoc($result)) {
			$block[$row['block_id']] = $row;
		}

		return $block;
	}

	function getApp($app_folder) {
		$app = array();

		$result = $this->Database->query("SELECT * FROM koma_applications WHERE application_path = '" . $app_folder . "'");
		if($row = $this->Database->fetchAssoc($result)) {
			return $row;
		}

		return false;
	}
}
?>